
//
//  YFMainController.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/8/24.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit
import SVProgressHUD

class YFMainController: UITabBarController {
    
    fileprivate var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        setupNewFeatureViews()
        
        delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(login), name: NSNotification.Name(rawValue: YFWeiboUserLoginNotification), object: nil)
    }
    
    deinit {
        ///< 定时器销毁
        timer?.invalidate()
        ///< 移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc fileprivate func login(n: Notification) {
        print("成功接收到通知: \(n)")
        print("此时的token: \(YFNetworkManager.shared.tokenModel.access_token ?? "")")
        var when = DispatchTime.now()
        if n.object != nil {
            when = when + 2
            SVProgressHUD.setDefaultMaskType(.black)
            SVProgressHUD.showInfo(withStatus: "账户过期, 请重新登录")
            
        }
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let vc = YFWeiboOAuthViewController()
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    // MARK: -该界面只支持竖屏
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    fileprivate lazy var composeButton : UIButton = UIButton.hm_button(withImageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button", highlightSuffix: "_highlighted")
    
    @objc fileprivate func composeButtonClick() {
//        print(#function)
//        
//        // MARK: -测试横屏
//        let vc = UIViewController()
//        vc.view.backgroundColor = UIColor.hm_random()
//        vc.title = "测试横屏"
//        let nav = UINavigationController(rootViewController: vc)
//        self .present(nav, animated: true, completion: nil)
        
        let composeView = YFComposeTypeView.composeTypeView()
        composeView.show {[weak composeView] (clsName) in
            guard let clsName = clsName ,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else {
                composeView?.removeFromSuperview()
                return
            }
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav, animated: true) {
                composeView?.removeFromSuperview()
            }
        }
    }
}

extension YFMainController {
    fileprivate func setupTimer() {
        ///< 如果用户没有登录, 则计时器不设置
        if !YFNetworkManager.shared.userLogon {
            return
        }
        if #available(iOS 10.0, *) {
            timer = Timer.scheduledTimer(withTimeInterval: 600, repeats: true, block: { (timer) in
                YFNetworkManager.shared.unreadCount { (count) in
                    self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
                    UIApplication.shared.applicationIconBadgeNumber = count
                }
            })
        } else {
            timer = Timer(timeInterval: 5, target: self, selector: #selector(checkNewMessage), userInfo: nil, repeats: true)
        }
    }
    
    @objc fileprivate func checkNewMessage() {
        YFNetworkManager.shared.unreadCount { (count) in
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}


extension YFMainController {
    
    fileprivate func setupComposeButton() {
        tabBar.addSubview(composeButton)
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        composeButton.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
    }
    
    
    fileprivate func setupChildControllers() {
        ///< 在现在的很多应用程序中, 界面的创建都依赖网络的json
        ///< 使用json来动态配置页面
        let jsonPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("main.json")
        
        var vcData = NSData(contentsOfFile: jsonPath) as Data?
        
        if vcData == nil {
            guard let jsonPath = Bundle.main.path(forResource: "main.json", ofType: nil) else {
                return
            }
            vcData = NSData(contentsOfFile: jsonPath) as Data?
        }
        
        
        var arrayM = [UIViewController]()
        
        if let vcData = vcData,
            let array = try! JSONSerialization.jsonObject(with: vcData, options: []) as? [[String : Any]]  {
            
            for dict in array {
                arrayM.append(controller(dict: dict))
            }
            viewControllers = arrayM
        }
    }
    
    private func controller(dict: [String : Any]) -> UIViewController {
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? YFBaseViewController.Type,
            let visitorInfoDict = dict["visitorInfo"] as? [String : String]
            else {
                return UIViewController()
        }
        
        let vc = cls.init()
        vc.title = title
        vc.visitorInfo = visitorInfoDict
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
        if #available(iOS 8.2, *) {
            vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 11, weight: UIFontWeightBold)], for: .normal)
        } else {
        }
        let nav = YFNavigationController(rootViewController: vc)
        return nav
    }
}

extension YFMainController {
    fileprivate func setupNewFeatureViews() {
        ///< 0. 如果用户未登录, 则直接return
        if !YFNetworkManager.shared.userLogon {
            return
        }
        ///< 1. 如果更新, 显示新特性, 否则显示欢迎
        let v = !isNewVersion ? YFWelcomeView.welcomeView() : YFNewFeatureView.newFeatureView()
        ///< 2. 添加视图
        v.frame = view.bounds
        view.addSubview(v)
    }
    
    
    /// extension 中可以有计算型属性, 不会占用存储空间
    /// 构造函数, 给属性分配空间
    
    /**
     * 版本号:
     * 在 AppStore 每次升级应用程序, 版本号都需要增加, 不能递减
     * 组成: 主版本号.次版本号.修订版本号
     * 主版本号: 意味着大的修改, 使用者也要做大的适应
     * 次版本号: 意味着小的修改, 某些函数和方法的使用或者参数有变化
     * 修订版本号: 框架 / 程序内部bug的修订, 不会对使用者造成任何的影响
     */
    private var isNewVersion: Bool {
        ///< 1. 取当前的版本号 // CFBundleShortVersionString
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""

        ///< 2. 取保存在'Document(iTunes备份) [最理想保存在用户偏好]' 目录中的之前的版本号
        let path: String = ("version" as NSString).hm_documentDirectory ?? ""
        
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        ///< 3. 将当前的版本号保存在沙盒
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        ///< 4. 返回两个版本号'是否一致'
        
        print("currentVersion : \(currentVersion)------sandboxVersion : \(sandboxVersion)")
        return currentVersion != sandboxVersion
//        return currentVersion == sandboxVersion
    }
}

extension YFMainController: UITabBarControllerDelegate {
    
    /// 将要选中的时候某个tabBar
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 即将要选中的控制器
    /// - Returns: 是否跳转到将要选择的控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        let idx = childViewControllers.index(of: viewController)
        let nav = childViewControllers[0]
        let vc = nav.childViewControllers[0] as? YFHomeViewController
        
        // 这个是表明当前的选中的控制器是第一个控制器
        // 且我即将选择的控制器跟当前的控制器是一样的
        if idx == selectedIndex && selectedIndex == 0 { ///< 进到这里的代码表示我重复点击了第一个控制器
            if let vc = vc {
                vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
                ///< 将tabBarButton的badgeValue和app图标的badgeNumber都清理掉
                vc.tabBarItem.badgeValue = nil
                UIApplication.shared.applicationIconBadgeNumber = 0
                
                ///< 这个延迟是保证在上面setContentOffset完成之后再刷新数据
                DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { 
                    vc.loadData()
                })
            }
        }
        return !viewController.isMember(of: UIViewController.self)
    }
}
